package safety

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/os/gmlock"
)

type (
	Func func(ctx context.Context) (interface{}, error)
)

// UserActionFreqTryLockFunc 接口用户操作频率控制-非阻塞性
func (s *sSafety) UserActionFreqTryLockFunc(ctx context.Context, key string, f Func) (interface{}, error) {
	if !gmlock.TryLock(key) {
		return nil, exception.New(`操作过于频繁，请稍后重试`)
	}
	defer gmlock.Unlock(key)
	return f(ctx)
}

// UserActionFreqLockFunc 接口用户操作频率控制-阻塞性
func (s *sSafety) UserActionFreqLockFunc(ctx context.Context, key string, f Func) (interface{}, error) {
	// 阻塞等待
	gmlock.Lock(key)
	defer gmlock.Unlock(key)
	return f(ctx)
}
